from sqlalchemy.orm import Mapped, mapped_column, relationship
from sqlalchemy import Integer, String, DateTime, ForeignKey
from ..database.db import Base
from datetime import datetime

class Folder(Base):
    __tablename__ = 'folders'

    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
    name: Mapped[str] = mapped_column(String(255), nullable=False)
    parent_id: Mapped[int | None] = mapped_column(
        Integer,
        ForeignKey('folders.id', ondelete='CASCADE', onupdate='RESTRICT'),
        nullable=True
    )
    user_id: Mapped[int] = mapped_column(
        Integer,
        ForeignKey('users.id', ondelete='CASCADE', onupdate='RESTRICT'),
        nullable=False
    )
    created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow)

    # 自关联关系
    parent: Mapped["Folder"] = relationship("Folder", remote_side=[id], back_populates="children")
    children: Mapped[list["Folder"]] = relationship("Folder", back_populates="parent")

    # 关联到用户
    user = relationship("Users", back_populates="folders")

    sources= relationship("FolderSources", back_populates="folder")

    def as_dict(self):
        data = {c.name: getattr(self, c.name) for c in self.__table__.columns}
        # 添加关联字段（如果有的话）
        if hasattr(self, 'source') and self.source:
            data['source'] = self.source.as_dict()
        return data
